package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.bouncycastle.crypto.generators.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class UserServiceImpl implements UserService {
    //注入dao
    @Autowired
    private UserDao userDao;

    @Override
    public User checkUser(String username) {
        //通过用户名查看是否有用户号
        User user=userDao.findByUserName(username);
        //上面只是查到一个用户,没有用户的集合
        //通过user来获取id,然后通过中间表来查
        Integer id = user.getId();
        Set <Role> roles = userDao.rolesselectById(id);
        //遍历角色
        for (Role role : roles) {
            Set<Permission> permissions= userDao.findByRoleID(role.getId());
            role.setPermissions(permissions);
        }
        user.setRoles(roles);
        return user;
    }

    @Override
    public String getUserImg(String username) {
        String img =userDao.selectImgByUsername(username);
        return img;
    }

    @Override
    public ArrayList<Menu> getMenu(String username) {
        ArrayList<Menu> list=userDao.selectMenuByUsername(username);
        for (Menu menu : list) {
            //根据menu获取其相应的子菜单集合
            List<Menu> children=userDao.findChildren(menu);
            menu.setChildren(children);
        }
        return list;
    }

    @Override
    public void change(String user, String passwordcode,String imgSet) {
        //把password转化为bcript方式加密
        BCryptPasswordEncoder bCryptPasswordEncoder =new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(passwordcode);
       //通过用户名去修改用户密码,把用户名和密码存到map
        Map<String,String> map =new HashMap <>();
        map.put("username",user);
        map.put("imgSet",imgSet);
        map.put("password",encode);
        userDao.updatePassword(map);
    }
}















